<template>
  <van-sticky>
    <van-nav-bar
        :title="`注册`"
        left-arrow
        @click-left="onClickLeft"
    >
    </van-nav-bar>
  </van-sticky>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="userAccount"
          name="userAccount"
          label="账号"
          placeholder="请填写账号"
          :rules="[{ required: true, message: '请填写账号' }]"
      />
      <van-field
          v-model="userPassword"
          type="password"
          name="userPassword"
          label="密码"
          placeholder="请填写密码"
          :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
          v-model="checkPassword"
          type="password"
          name="checkPassword"
          label="校验密码"
          placeholder="请再输入一次密码"
          :rules="[{ required: true, message: '请再输入一次密码' }]"
      />
      <van-field name="radio" label="性别">
        <template #input>
          <van-radio-group v-model="gender" direction="horizontal">
            <van-radio name="1">男</van-radio>
            <van-radio name="0">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="请填写用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
          v-model="fullAddress"
          name="location"
          label="位置信息"
          readonly
          placeholder="点击选择地理位置"
          :rules="[{ required: true, message: '请选择位置' }]"
          input-align="left"
          class="address-field"
      >
        <template #input>
          <div class="address-content">
            {{ fullAddress || '请选择位置' }}
          </div>
        </template>
        <template #button>
          <van-button
              size="small"
              type="primary"
              @click="openMap"
              :loading="mapLoading"
          >
            {{ address ? '重新选择' : '选择位置' }}
          </van-button>
        </template>
      </van-field>

      <!-- 经度纬度显示字段 -->
      <van-field
          v-model="longitude"
          name="经度"
          label="经度"
          readonly
          placeholder="自动获取经度"
      />
      <van-field
          v-model="dimension"
          name="纬度"
          label="纬度"
          readonly
          placeholder="自动获取纬度"
      />

      <!-- 地图弹窗 -->
      <van-popup
          v-model:show="showMap"
          position="bottom"
          round
          :style="{ height: '90%' }"
          @open="handlePopupOpen"
      >
      <div
          v-show="mapLoaded"
          class="map-container"
          id="map-container"      style="visibility: visible"
      ></div>
      <van-loading
          v-if="!mapLoaded"
          type="spinner"
          vertical
      >
        地图加载中...
      </van-loading>
      <van-button
          type="primary"
          block
          @click="confirmLocation"      style="position: absolute; bottom: 0;"
          :loading="confirmLoading"
      >
        确认位置
      </van-button>
      </van-popup>
    </van-cell-group>


    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        注册
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
let geocoder: any = null;
import {nextTick, ref} from "vue";
import {useRouter} from "vue-router";
import {showToast} from "vant";

const router = useRouter();

const fullAddress = ref('');
const userAccount = ref('');
const userPassword = ref('');
const checkPassword = ref('');
const gender = ref('');
const avatarUrl = ref('');
const username = ref('');
const phone = ref('');
const longitude = ref('');
const dimension = ref('');
const address = ref('');


const onSubmit = () => {
  const registerUserParam = {
    userAccount: userAccount.value,
    userPassword: userPassword.value,
    checkPassword: checkPassword.value,
    gender: gender.value,
    avatarUrl: avatarUrl.value,
    username: username.value,
    phone: phone.value,
    longitude: longitude.value,
    dimension: dimension.value,
  };

  router.push({
    path: '/user/registerTags',
    query: {
      registerUser: JSON.stringify(registerUserParam),
    }
  });
};

const onClickLeft = () => {
  router.back();
};

// 地图相关状态
const showMap = ref(false);
const mapLoading = ref(false);
const confirmLoading = ref(false);
let map: any = null;

// 高德地图配置
declare global {
  interface Window {
    AMap: any;
    _AMapSecurityConfig: { securityJsCode: string };
  }
}

const AMapKey = '4dbf20c5c360261486e52aaf919ae59a';
window._AMapSecurityConfig = {
  securityJsCode: 'edbfc60638f8587cc76ccb22d0cebf90'
};

// 点击处理方法
const handleMapClick = (e: any) => {
  if (!map) return;

  // 安全移除旧标记
  try {
    if (marker && map.remove) {
      map.remove(marker);
    }
  } catch (err) {
    console.warn('移除标记时发生错误:', err);
  } finally {
    marker = null;
  }

  // 创建新标记
  marker = new AMap.Marker({
    position: e.lnglat,
    map: map // 显式指定父级地图
  });

  // 更新坐标
  longitude.value = e.lnglat.getLng().toFixed(6);
  dimension.value = e.lnglat.getLat().toFixed(6);

  // 使用setCenterSafe方法
  setCenterSafe(e.lnglat);
};

// 新增安全定位方法
const setCenterSafe = (lnglat: any) => {
  try {
    if (map && map.setCenter) {
      map.setCenter(lnglat);
    }
  } catch (err) {
    console.error('地图定位失败:', err);
  }
};

// 确保已定义marker变量
let marker: any = null;

// 地图初始化
const initMap = async () => {
  try {
    // 检查容器存在性
    const container = document.getElementById('map-container');
    if (!container) {
      showToast('地图容器未找到');
      return;
    }

    // 动态加载SDK
    if (!window.AMap) {
      await new Promise<void>((resolve, reject) => {
        const script = document.createElement('script');
        script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMapKey}&plugin=AMap.Geocoder`; // 修正SDK版本

        // 增加超时处理
        const timer = setTimeout(() => {
          showToast('地图加载超时');
          reject();
        }, 10000);

        script.onload = () => {
          clearTimeout(timer);
          console.log('AMap SDK加载成功');
          // 高德地图需要额外初始化时间
          setTimeout(() => {
            mapLoaded.value = true;
            resolve();
          }, 500);
        };

        script.onerror = (err) => {
          clearTimeout(timer);
          console.error('AMap SDK加载失败:', err);
          showToast('地图库加载失败');
          reject(err);
        };

        document.head.appendChild(script);
      });
    }

    // 销毁旧实例
    if (map) {
      try {
        map.destroy();
      } catch (err) {
        console.warn('地图销毁失败:', err);
      }
      map = null;
    }

    // 创建新地图实例

    // 创建新地图实例
    map = new AMap.Map('map-container', {
      zoom: 16,
      viewMode: '3D'
    });

    // 初始化地理编码器
    geocoder = new AMap.Geocoder();

    // 添加地图事件
    map.on('complete', () => console.log('地图渲染完成'));
    map.on('click', handleMapClick);

    // 自动定位
    await autoLocation();

  } catch (error) {
    console.error('地图初始化失败:', error);
  }
};

// 新增弹窗打开处理
const handlePopupOpen = async () => {
  try {
    mapLoading.value = true;
    await nextTick();
    await initMap();
    // 强制重绘地图
    setTimeout(() => map?.setFitView(), 300);
  } catch (error) {
    showMap.value = false;
  } finally {
    mapLoading.value = false;
  }
};

const autoLocation = async () => {
  try {
    const position = await new Promise<GeolocationPosition>((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(
          resolve,
          error => {
            console.log('定位错误代码:', error.code);
            showToast('自动定位失败，请手动选择');
            reject(error);
          },
          {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0
          }
      );
    });

    const lng = position.coords.longitude;
    const lat = position.coords.latitude;

    if (map) {
      map.setCenter([lng, lat]);
      handleMapClick({
        lnglat: {
          getLng: () => lng,
          getLat: () => lat
        }
      });
    }
  } catch (error) {
    console.error('自动定位失败:', error);
  }
};


// 新增状态变量
const mapLoaded = ref(false);

// 打开地图弹窗
const openMap = async () => {
  try {
    mapLoading.value = true;
    await nextTick();

    // 确保弹窗完全渲染后再初始化地图
    await new Promise(resolve => setTimeout(resolve, 100));

    if (!window.AMap) {
      await initMap();
    } else {
      // 强制重新渲染地图容器
      if (map) map.destroy();
      await initMap();
    }

    showMap.value = true;
  } catch (error) {
    console.error('地图初始化失败:', error);
    showToast('地图加载失败，请检查网络');
  } finally {
    mapLoading.value = false;
  }
};

// 确认位置
const confirmLocation = async () => {
  if (!longitude.value || !dimension.value) {
    showToast('请先在地图上选择位置');
    return;
  }

  try {
    confirmLoading.value = true;
    const result = await new Promise<any>((resolve) => {
      geocoder.getAddress([longitude.value, dimension.value],
          (status: string, result: any) => {
            resolve(status === 'complete' ? result : null);
          }
      );
    });

    if (result?.regeocode) {
      // 结构化地址信息
      const { province, city, district, township, streetNumber } =
          result.regeocode.addressComponent;

      // 构建完整地址
      const baseAddress = [
        province,
        city,
        district,
        township,
        streetNumber.street,
        streetNumber.number
      ].filter(Boolean).join('');

      // 添加POI信息
      const poiInfo = result.regeocode.pois?.[0]?.name
          ? `（靠近：${result.regeocode.pois[0].name}）`
          : '';

      // 组合完整地址
      fullAddress.value = `${baseAddress}${poiInfo}`;

      // 显示完整地址（控制台验证）
      console.log('完整地址信息：', {
        base: baseAddress,
        poi: poiInfo,
        full: fullAddress.value
      });
      showToast('位置已确认');
      showMap.value = false;
    }
  } catch (error) {
    console.error('地址解析错误:', error);
    showToast('获取地址失败');
  } finally {
    confirmLoading.value = false;
    showMap.value = false;
  }
};

</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh !important; /* 强制全屏高度 */
  min-height: 500px;
  background: #f5f5f5;
}

van-popup {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  z-index: 9999 !important;
}

:deep(.van-overlay) {
  z-index: 9998;
}

:deep(.amap-logo),
:deep(.amap-copyright) {
  display: none !important;
}

.address-field :deep(.van-field__body) {
  height: auto;
  min-height: 44px;
}

.address-content {
  width: 100%;
  padding: 4px 0;
  line-height: 1.5;
  word-break: break-all;
  white-space: pre-wrap;
  color: #323233;

  /* 多行显示时保持对齐 */
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 小屏适配 */
@media (max-width: 375px) {
  .address-content {
    font-size: 14px;
    -webkit-line-clamp: 4;
  }
}
</style>